import React, { useMemo } from 'react';
import clsx from 'clsx';
import FlexContext from './FlexContext';
import { FlexProps } from './PropsType';
import useNamespace from '../utils/useNamespace';

const Flex: React.FC<FlexProps> = ({
  direction,
  wrap,
  justify,
  align,
  gutter = 0,
  style,
  className,
  children,
  ...rest
}) => {
  const [bem] = useNamespace('flexbox');
  const resolvedGutter = useMemo<[number, number]>(() => {
    if (Array.isArray(gutter)) {
      return [gutter[0] ?? 0, gutter[1] ?? 0];
    }
    const value = gutter ?? 0;
    return [value, 0];
  }, [gutter]);

  const rowStyle = {
    ...(resolvedGutter[0]! > 0
      ? {
          marginLeft: resolvedGutter[0]! / -2,
          marginRight: resolvedGutter[0]! / -2,
        }
      : {}),
    ...(resolvedGutter[1]! > 0
      ? {
          marginTop: resolvedGutter[1]! / -2,
          marginBottom: resolvedGutter[1]! / 2,
        }
      : {}),
    ...style,
  };

  const wrapCls = clsx(
    className,
    bem([
      direction,
      wrap,
      justify ? `justify-${justify}` : false,
      align ? `align-${align}` : false,
    ]),
  );

  return (
    <FlexContext.Provider value={{ gutter: resolvedGutter }}>
      <div className={wrapCls} style={rowStyle} {...rest}>
        {children}
      </div>
    </FlexContext.Provider>
  );
};

export default Flex;
